//
//  ConfirmOrderViewController.m
//  MobileShoppingMall
//
//  Created by 冯传昌 on 2021/4/29.
//  Copyright © 2021 冯传昌. All rights reserved.
//

#import "ConfirmOrderViewController.h"

#import "ConfirmOrderModel.h"
#import "OrdersModel.h"
#import "ConfirmOrderCell.h"

#import "SelectAddressView.h"

#import "AddressModel.h"

#import "AddressListViewController.h"
#import "WechatPayManager.h"

#import "MyOrdersViewController.h"

@interface ConfirmOrderViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;

@property (nonatomic,strong) NSMutableArray *dataSourceArr;//UI 数据源数组

@property (nonatomic,strong) NSMutableArray *allGoodsArr;//所有商品数组

@property (nonatomic,strong) SelectAddressView *headerView;

@property (nonatomic,strong) AddressModel *currentModel;

@property (nonatomic,strong) UIView *bottomView;

@property (nonatomic,strong) UILabel *totalPriceLB;//总价lb

@property (nonatomic,strong) UILabel *goodsNumberLB;//商品总数量lb

@property (nonatomic,strong) UIButton *submitOrdersBtn;//提交订单btn

@property (nonatomic,assign) NSInteger currentCredit;//当前剩余TB 余额

@property (nonatomic,assign) NSInteger totalTBPrice;//当前支付所需TB

@property (nonatomic,assign) NSInteger falseJumpCount;//支付失败跳转次数

@property (nonatomic,assign) NSInteger successJumpCount;//支付成功跳转次数

@end

@implementation ConfirmOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.topTitle = @"确认订单";
    self.view.backgroundColor = MainBackColor;
    self.topNavView.backgroundColor = MainBackColor;
    self.dataSourceArr = [NSMutableArray array];
    self.allGoodsArr = [NSMutableArray array];
    self.currentModel = nil;
    self.falseJumpCount = 0;
    self.successJumpCount = 0;
    
    [self initUI];
    [self getData];
    
    //接受支付结果通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResultClick:) name:@"wechatPayResultNotification" object:nil];
    //接受支付结果通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResultClick:) name:@"wechatPayResultNotificationSuccess" object:nil];
}
#pragma mark - noti
-(void)payResultClick:(NSNotification *)noti{
    NSDictionary *dic = (NSDictionary *)noti.userInfo;
    if ([dic[@"payStatus"] intValue] == 0) {
        if (self.successJumpCount == 0) {
            [self paySuccessClick];
        }
    }else{
        if (self.falseJumpCount == 0) {
            [self payFalse:dic[@"payResult"]];
        }
    }
}
#pragma mark - data
-(void)getData{
    self.dataSourceArr = [NSMutableArray array];
    self.allGoodsArr = [NSMutableArray array];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"module"] = self.module;
    if ([self.module isEqualToString:@"cart"]) {
        params[@"skuIds"] = [self.skuIds componentsJoinedByString:@","];
    }else{
        params[@"skuId"] = @(self.skuId);
        params[@"number"] = @(1);
    }
    [NetWorkingOrder ordersConfirmWithParams:params withSuccessBlock:^(id  _Nonnull responseObj) {
        NSDictionary *data = responseObj[@"data"];
        NSArray *carts = data[@"products"];
        
        for (NSDictionary *dic in carts) {
            ConfirmOrderModel *model = [ConfirmOrderModel paraWithDict:dic];
            [self.dataSourceArr addObject:model];
        }
        [self updateBottomInfo];
        self.currentCredit = [data[@"credit"] integerValue];
        id deliver = data[@"deliver"];
        if ([deliver isNull]==NO) {
            NSDictionary *deliverDict = (NSDictionary *)deliver;
            if ([deliverDict.allKeys containsObject:@"province"]) {
                NSDictionary *dic1 = (NSDictionary *)deliver;
                self.currentModel = [AddressModel paraWithDict:dic1];
                self.headerView.model = self.currentModel;
            }
        }
        [self.tableView reloadData];
    }];
}
-(void)updateBottomInfo{
    NSInteger goodsNumber = 0;
    NSInteger tbPirce = 0;
    float price = 0;
    for (ConfirmOrderModel *model in self.dataSourceArr) {
        for (OrdersModel *ordersM in model.products) {
            goodsNumber = goodsNumber + ordersM.number;
            tbPirce = tbPirce + ordersM.number*ordersM.tbprice;
            price = price + ordersM.number * ordersM.price;
            [self.allGoodsArr addObject:ordersM];
        }
    }
    self.totalTBPrice = tbPirce;
    self.totalPriceLB.text = [Configuration getTotalPriceWithPrice:price withTbPrice:tbPirce];
    self.goodsNumberLB.text = [NSString stringWithFormat:@"共%ld件",(long)goodsNumber];
}
#pragma mark - UI
-(void)initUI{
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.totalPriceLB];
    [self.bottomView addSubview:self.goodsNumberLB];
    [self.bottomView addSubview:self.submitOrdersBtn];
    
    WEAKSELF(self);
    [self.headerView setSelectAddressBlock:^{
        [weakSelf toSelectAddressClick];
    }];
}
#pragma mark - lazy
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kHeight_NavBar, ScreenWidth, ScreenHeight - kHeight_NavBar - kSafe_Bottom - 50) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = MainBackColor;
        [_tableView setTableHeaderView:self.headerView];
    }
    return _tableView;
}
-(SelectAddressView *)headerView{
    if (!_headerView) {
        _headerView = [[SelectAddressView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 117)];
    }
    return _headerView;
}
- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenHeight-50-kSafe_Bottom, ScreenWidth, 50+kSafe_Bottom)];
        _bottomView.backgroundColor = UIColor.whiteColor;
        UIView *lineV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 1)];
        lineV.backgroundColor = MainBackColor;
        [_bottomView addSubview:lineV];
    }
    return _bottomView;
}
//商品价格lb
-(UILabel *)totalPriceLB{
    if (!_totalPriceLB) {
        _totalPriceLB = [[UILabel alloc] initWithFrame:CGRectMake(16, 16, 150, 18)];
        _totalPriceLB.textAlignment = NSTextAlignmentLeft;
        _totalPriceLB.textColor = RGB(255, 34, 21);
        _totalPriceLB.font = FontSetWithWeight(15, 0.2f);
    }
    return _totalPriceLB;
}
//商品数量
- (UILabel *)goodsNumberLB{
    if (!_goodsNumberLB) {
        _goodsNumberLB = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth - 115 - 90, 16, 80, 18)];
        _goodsNumberLB.textAlignment = NSTextAlignmentRight;
        _goodsNumberLB.textColor = MainBlackTextColor;
        _goodsNumberLB.font = FontSet(14);
    }
    return _goodsNumberLB;
}
- (UIButton *)submitOrdersBtn{
    if (!_submitOrdersBtn) {
        _submitOrdersBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _submitOrdersBtn.frame = CGRectMake(ScreenWidth - 105, 7, 90, 36);
        _submitOrdersBtn.clipsToBounds = YES;
        _submitOrdersBtn.layer.cornerRadius = 18;
        _submitOrdersBtn.backgroundColor = MainThemeColor;
        [_submitOrdersBtn.titleLabel setFont:FontSet(14)];
        [_submitOrdersBtn setTitleColor:UIColor.whiteColor forState:normal];
        [_submitOrdersBtn setTitle:@"提交订单" forState:normal];
        [_submitOrdersBtn addTarget:self action:@selector(submitOrderClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _submitOrdersBtn;
}
#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ConfirmOrderModel *model = self.dataSourceArr[indexPath.row];
    return model.cellHeight;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ConfirmOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConfirmOrderCell"];
    if (!cell) {
        cell = [[ConfirmOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ConfirmOrderCell"];
    }
    cell.model = self.dataSourceArr[indexPath.row];
    
    [cell setUpdateMessageBlock:^(ConfirmOrderModel * _Nonnull confirmOrderM) {
        [self updateDataSourceWithModel:confirmOrderM];
    }];
    return cell;
}
#pragma mark - SEL
//选择地址
-(void)toSelectAddressClick{
    [self.view endEditing:YES];
    AddressListViewController *vc = [[AddressListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    WEAKSELF(self);
    [vc setSelectAddressBlock:^(AddressModel * _Nonnull addressM) {
        weakSelf.currentModel = addressM;
        weakSelf.headerView.model = addressM;
    }];
}
-(void)updateDataSourceWithModel:(ConfirmOrderModel *)model{
    for (int i = 0; i<self.dataSourceArr.count; i++) {
        ConfirmOrderModel *conM = self.dataSourceArr[i];
        if ([conM.company isEqualToString:model.company]) {
            [self.dataSourceArr replaceObjectAtIndex:i withObject:model];
        }
    }
    [self.tableView reloadData];
}
//提交订单
-(void)submitOrderClick{
    [self.view endEditing:YES];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self submitClick];
    });
}
-(void)submitClick{
    if (self.currentModel != nil && self.currentModel.province.length > 0) {
    }else{
        [[XNProgressHUD shared] showWithTitle:@"请选择收货地址"];
        return;
    }
    if (self.currentCredit < self.totalTBPrice) {
        [[XNProgressHUD shared] showWithTitle:@"您的余额不足以购买商品了，请及时充值！"];
        return;
    }
    NSMutableArray *notes = [NSMutableArray array];
    for (ConfirmOrderModel *model in self.dataSourceArr) {
        [notes addObject:@{@"note":[model.leaveMessage isEmpty] == NO ? model.leaveMessage:@""}];
    }
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"module"] = self.module;
    params[@"deliverId"] = @(self.currentModel.ID);
    params[@"notes"] = [Configuration arrayToJSONString:notes];
    
    if ([self.module isEqualToString:@"cart"]) {
        params[@"skuIds"] = [self.skuIds componentsJoinedByString:@","];
    }else{
        params[@"skuId"] = [NSString stringWithFormat:@"%ld",(long)self.skuId];
        params[@"number"] = @"1";
    }
    params[@"source"] = @"app";
    
    [[XNProgressHUD shared] showLoadingWithTitle:@"正在支付..."];
    [NetWorkingOrder placeOrdersWithParams:params withSuccessBlock:^(id  _Nonnull responseObj) {
        NSDictionary *data = responseObj[@"data"];
        if ([data.allKeys containsObject:@"noncestr"]) {
            [WechatPayManager handleWechatPayWithPayDic:data];
        }else{
            [self paySuccessClick];
        }
    }];
}
//支付成功 跳转订单列表页面
-(void)paySuccessClick{
    self.successJumpCount = 1;
    if (object_getClassName([[Configuration getCurrentVC] class]) != object_getClassName([ConfirmOrderViewController class])) {
        return;
    }
    [[XNProgressHUD shared] showSuccessWithTitle:@"支付成功!"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popToRootViewControllerAnimated:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            MyOrdersViewController *orderVC = [[MyOrdersViewController alloc] init];
            orderVC.sourceType = 0;
            [[Configuration getCurrentVC].navigationController pushViewController:orderVC animated:YES];
        });
    });
}
//支付失败 跳转代付款订单列表页面
-(void)payFalse:(NSString *)falseReason{
    self.falseJumpCount = 1;
    if (object_getClassName([[Configuration getCurrentVC] class]) != object_getClassName([ConfirmOrderViewController class])) {
        return;
    }
    [[XNProgressHUD shared] showErrorWithTitle:falseReason];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.navigationController popToRootViewControllerAnimated:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            MyOrdersViewController *orderVC = [[MyOrdersViewController alloc] init];
            orderVC.sourceType = 1;
            [[Configuration getCurrentVC].navigationController pushViewController:orderVC animated:YES];
        });
    });
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

@end





